﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using TierApplication;
using System.Data;
using DevExpress.Web.ASPxEditors;
using System.Drawing;

public partial class System_Product_ProductImp : BasePage
{
    #region private
    T_PRODUCT mProduct = new T_PRODUCT();
    string ProductImageFolder = "..\\..\\ProductImages\\";
    private const string inputQueryStringIDKey = "IMPBATCHNO";
    private const string inputQueryStringPageModeKey = "pagemode";
    private const string currentPageModeKey = "CurrentPageMode";
    private const string mDataModel = "mDataModel";
    private const string ImpBatchNo = "ImpBatchNo";


    public enum PageMode
    {
        add,
        update,
        query,
        audit
    }
    private Nullable<PageMode> pm;
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {

        if (Page.IsPostBack)
        {
            pm = ViewState[currentPageModeKey] as Nullable<PageMode>;
            if (gridSearchResult.IsCallback)
            {
                DataTable dt = (DataTable)ViewState["data"];
                if (dt != null)
                {
                    gridSearchResult.DataSource = dt;
                    gridSearchResult.DataBind();
                }

            }
        }
        else
        {
            SetEnabled(false);
            BindBandwidth();
            BindLifeTime();
            BindSchool();
            BindCategoryId();

            this.txtIMPBATCHNO.Text = Page.Request.QueryString[inputQueryStringIDKey];
            this.pagemode.Value = Page.Request.QueryString[inputQueryStringPageModeKey];

            switch (this.pagemode.Value.ToLower().Trim())
            {
                case "add":
                    pm = PageMode.add;
                    break;
                case "update":
                    pm = PageMode.update;
                    break;
                case "audit":
                    pm = PageMode.audit;
                    break;
                case "query":
                    pm = PageMode.query;
                    break;
                default:
                    pm = PageMode.add;
                    break;
            }
            ViewState[currentPageModeKey] = pm;

            if (pm == PageMode.add)
            {
                btnAudit.Visible = false;
                btnCancelAudit.Visible = false;
            }

            if (!string.IsNullOrEmpty(this.txtIMPBATCHNO.Text.Trim()))
            {
                LoadImpProductItemByBatchNo(this.txtIMPBATCHNO.Text.Trim());
                ViewState[ImpBatchNo] = this.txtIMPBATCHNO.Text.Trim();
                if (pm == PageMode.audit)
                {
                    btnID.Visible = false;
                    txtFileUp.Visible = false;
                    btnFileUpLoad.Visible = false;
                    btnCardDelete.Visible = false;
                    btnProductSave.Visible = false;
                    btnSubmitAudit.Visible = false;

                    btnAudit.Visible = true;
                    btnCancelAudit.Visible = true;

                    tlTitle.InnerText = "商品导入信息审核";
                }

                if ((pm == PageMode.add) || (pm == PageMode.update))
                {
                    btnID.Visible = true;
                    txtFileUp.Visible = true;
                    btnFileUpLoad.Visible = true;
                    btnCardDelete.Visible = true;
                    btnProductSave.Visible = true;
                    btnSubmitAudit.Visible = true;

                    btnAudit.Visible = false;
                    btnCancelAudit.Visible = false;
                }

                if (pm == PageMode.query)
                {
                    btnID.Visible = false;
                    txtFileUp.Visible = false;
                    btnFileUpLoad.Visible = false;
                    btnCardDelete.Visible = false;
                    btnProductSave.Visible = false;
                    btnSubmitAudit.Visible = false;

                    btnAudit.Visible = false;
                    btnCancelAudit.Visible = false;
                    tlTitle.InnerText = "商品导入明细信息";
                }

            }
        }


    }

    private void SetEnabled(bool flag)
    {
        txtPRODUCTNAME.Enabled = flag;
        ddlSCHOOLID.Enabled = flag;
        ddlBANDWIDTH.Enabled = flag;
        ddlLIFETIME.Enabled = flag;
        ddlCATEGORYID.Enabled = flag;
        //this.txtPURCHASEPRICE.Enabled = flag;
        this.txtMARKETPRICE.Enabled = flag;
        this.txtDISCOUNT.Enabled = flag;
        this.txtDISCOUNTPRICE.Enabled = flag;
        this.txtUNITPRICE.Enabled = flag;

        txtPRODUCTNAME.BackColor = Color.FromArgb(224, 224, 224);
        ddlSCHOOLID.BackColor = Color.FromArgb(224, 224, 224);
        ddlBANDWIDTH.BackColor = Color.FromArgb(224, 224, 224);
        ddlLIFETIME.BackColor = Color.FromArgb(224, 224, 224);
        ddlCATEGORYID.BackColor = Color.FromArgb(224, 224, 224);
        txtMARKETPRICE.BackColor = Color.FromArgb(224, 224, 224);
        txtDISCOUNT.BackColor = Color.FromArgb(224, 224, 224);
        txtDISCOUNTPRICE.BackColor = Color.FromArgb(224, 224, 224);
        txtUNITPRICE.BackColor = Color.FromArgb(224, 224, 224);
    }

    private void LoadProduct(String ProductID)
    {
        ListEditItem theselected;
        T_PRODUCT mProduct = new T_PRODUCT();
        mProduct.GetModel(ProductID);
        ViewState[mDataModel] = mProduct;


        txtPRODUCTNAME.Text = mProduct.PRODUCTNAME;

        if (!String.IsNullOrEmpty(mProduct.SCHOOLID))
        {
            theselected = ddlSCHOOLID.Items.FindByValue(mProduct.SCHOOLID);
            if (theselected != null)
            {
                ddlSCHOOLID.SelectedItem = theselected;
            }
        }

        if (!String.IsNullOrEmpty(mProduct.BANDWIDTH))
        {
            theselected = ddlBANDWIDTH.Items.FindByValue(mProduct.BANDWIDTH);
            if (theselected != null)
            {
                ddlBANDWIDTH.SelectedItem = theselected;
            }
        }

        if (!String.IsNullOrEmpty(mProduct.LIFETIME))
        {
            theselected = ddlLIFETIME.Items.FindByValue(mProduct.LIFETIME);
            if (theselected != null)
            {
                ddlLIFETIME.SelectedItem = theselected;
            }
        }

        if (!String.IsNullOrEmpty(mProduct.CATEGORYID))
        {
            theselected = ddlCATEGORYID.Items.FindByValue(mProduct.CATEGORYID);
            if (theselected != null)
            {
                ddlCATEGORYID.SelectedItem = theselected;
            }
        }

        this.txtPURCHASEPRICE.Text = mProduct.PURCHASEPRICE.ToString();
        this.txtMARKETPRICE.Text = mProduct.MARKETPRICE.ToString();
        this.txtDISCOUNT.Text = mProduct.DISCOUNT.ToString();
        this.txtDISCOUNTPRICE.Text = mProduct.DISCOUNTPRICE.ToString();
        this.txtUNITPRICE.Text = mProduct.UNITPRICE.ToString();
        //this.txtPRODUCTIMAGE.Text = mProduct.PRODUCTIMAGE;
        this.ProductImage.Src = ProductImageFolder + mProduct.PRODUCTIMAGE;
        this.bigImg.HRef = ProductImageFolder + mProduct.PRODUCTIMAGE;
        this.ProductImage.Width = 100;
        this.ProductImage.Height = 100;

        //this.txtREMARK.Text = mProduct.REMARK;
        //this.txtREMARK1.Text = mProduct.REMARK1;


    }

    private void LoadImpProductItemByBatchNo(String IMPBATCHNO)
    {
        ListEditItem theselected;
        T_PRODUCTIMP mProductImp = new T_PRODUCTIMP();
        mProductImp.GetModel(IMPBATCHNO);

        txtIMPDATE.Date = mProductImp.IMPDATE.Value;
        txtIMPSTATUS.Text = P_DDCODE.GetCodeNameByCodeID(P_DDCODE.DDType.ImpStatus.ToString(), mProductImp.IMPSTATUS);
        txtLEFTTIME.Date = mProductImp.LEFTTIME.Value;
        txtProductId.Text = mProductImp.PRODUCTID;

        //ViewState[mDataModel] = mProductItem;
        txtPRODUCTNAME.Text = mProductImp.PRODUCTNAME;

        if (!String.IsNullOrEmpty(mProductImp.SCHOOLID))
        {
            theselected = ddlSCHOOLID.Items.FindByValue(mProductImp.SCHOOLID);
            if (theselected != null)
            {
                ddlSCHOOLID.SelectedItem = theselected;
            }
        }

        if (!String.IsNullOrEmpty(mProductImp.BANDWIDTH))
        {
            theselected = ddlBANDWIDTH.Items.FindByValue(mProductImp.BANDWIDTH);
            if (theselected != null)
            {
                ddlBANDWIDTH.SelectedItem = theselected;
            }
        }

        if (!String.IsNullOrEmpty(mProductImp.LIFETIME))
        {
            theselected = ddlLIFETIME.Items.FindByValue(mProductImp.LIFETIME);
            if (theselected != null)
            {
                ddlLIFETIME.SelectedItem = theselected;
            }
        }

        if (!String.IsNullOrEmpty(mProductImp.CATEGORYID))
        {
            theselected = ddlCATEGORYID.Items.FindByValue(mProductImp.CATEGORYID);
            if (theselected != null)
            {
                ddlCATEGORYID.SelectedItem = theselected;
            }
        }

        this.txtPURCHASEPRICE.Text = mProductImp.PURCHASEPRICE.ToString();
        this.txtMARKETPRICE.Text = mProductImp.MARKETPRICE.ToString();
        this.txtDISCOUNT.Text = mProductImp.DISCOUNT.ToString();
        this.txtDISCOUNTPRICE.Text = mProductImp.DISCOUNTPRICE.ToString();
        this.txtUNITPRICE.Text = mProductImp.UNITPRICE.ToString();
        this.ProductImage.Src = ProductImageFolder + mProductImp.PRODUCTIMAGE;
        this.bigImg.HRef = ProductImageFolder + mProductImp.PRODUCTIMAGE;
        this.ProductImage.Width = 100;
        this.ProductImage.Height = 100;


        //this.txtREMARK.Text = mProduct.REMARK;
        //this.txtREMARK1.Text = mProduct.REMARK1;

        //***********************************************//
        T_PRODUCTITEM mProductItem = new T_PRODUCTITEM();
        DataSet ds = mProductItem.GetProductItemListByImpBatchNo(IMPBATCHNO);
        gridSearchResult.DataSource = ds.Tables[0];
        gridSearchResult.DataBind();
    }

    private void BindBandwidth()
    {
        DataSet ds = P_DDCODE.GetListByType(P_DDCODE.DDType.Bandwidth.ToString());
        this.ddlBANDWIDTH.DataSource = ds.Tables[0].DefaultView;
        this.ddlBANDWIDTH.TextField = "CodeName";
        this.ddlBANDWIDTH.ValueField = "CodeID";
        this.ddlBANDWIDTH.DataBind();
    }

    private void BindLifeTime()
    {
        DataSet ds = P_DDCODE.GetListByType(P_DDCODE.DDType.LifeTime.ToString());
        this.ddlLIFETIME.DataSource = ds.Tables[0].DefaultView;
        this.ddlLIFETIME.TextField = "CodeName";
        this.ddlLIFETIME.ValueField = "CodeID";
        this.ddlLIFETIME.DataBind();
    }

    private void BindCategoryId()
    {
        DataSet ds = P_DDCODE.GetListByType(P_DDCODE.DDType.CategoryId.ToString());
        this.ddlCATEGORYID.DataSource = ds.Tables[0].DefaultView;
        this.ddlCATEGORYID.TextField = "CodeName";
        this.ddlCATEGORYID.ValueField = "CodeID";
        this.ddlCATEGORYID.DataBind();
    }

    private void BindSchool()
    {
        T_SCHOOL mSchool = new T_SCHOOL();
        DataSet ds = mSchool.GetList("");
        this.ddlSCHOOLID.DataSource = ds;
        this.ddlSCHOOLID.ValueField = "SCHOOLID";
        this.ddlSCHOOLID.TextField = "SCHOOLNAME";
        this.ddlSCHOOLID.DataBind();
        this.ddlSCHOOLID.Items.Insert(0, new ListEditItem("(全部)", ""));
    }

    protected void btnProductSave_Click(object sender, EventArgs e)
    {
        string ac_impbatchno = (string)ViewState[ImpBatchNo];
        string ac_userid = base.CurrentUserCode;
        string ac_productid = this.txtProductId.Text;
        string ac_lifedate = txtLEFTTIME.Date.ToString("yyyyMMdd");
        Int32 ai_Result = 0;
        string ac_Result = "";
        double an_PURCHASEPRICE = double.Parse(txtPURCHASEPRICE.Text);


        if (TierService.Utility.IsNullorEmpty(ac_impbatchno))
        {
            TierService.MessageBox.Show(this, "没有导入卡号信息,不能保存");
            return;
        }

        try
        {
            if (txtIMPBATCHNO.Text == "")
            {
                DataTable dt = (DataTable)ViewState["data"];
                int iCardCount = dt.Rows.Count;

                if (iCardCount == 0)
                {
                    TierService.MessageBox.Show(this, "没有导入卡号信息,不能保存");
                    return;
                }
            }
        }
        catch (Exception)
        {
            TierService.MessageBox.Show(this, "没有导入卡号信息,不能保存");
            return;
        }


        T_IMPCARD.ImpPrudoctItem(ac_impbatchno, ac_userid, ac_productid, an_PURCHASEPRICE, ac_lifedate, ref ai_Result, ref ac_Result);
        if (ai_Result != 0)
        {
            TierService.MessageBox.Show(this, ac_Result);
            return;
        }
        txtIMPBATCHNO.Text = ac_impbatchno;

        //this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script language='javascript'>alert('导入成功');window.returnValue='ok';window.opener=null; window.close();</script>");
        this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script language='javascript'>alert('导入成功');</script>");
    }

    protected void btnFileUpLoad_Click(object sender, EventArgs e)
    {
        Boolean fileOk = false;
        string path = Server.MapPath("~/UpLoadFile/");
        string sFullFileName = "";
        //判断是否已经选取文件
        if (txtFileUp.HasFile)
        {
            #region 判断文件合法性
            //取得文件的扩展名,并转换成小写
            string fileExtension = System.IO.Path.GetExtension(txtFileUp.FileName).ToLower();
            //限定只能上传jpg和gif图片
            string[] allowExtension = { ".txt" };
            //对上传的文件的类型进行一个个匹对
            for (int i = 0; i < allowExtension.Length; i++)
            {
                if (fileExtension == allowExtension[i])
                {
                    fileOk = true;
                    break;
                }
            }
            //对上传文件的大小进行检测，限定文件最大不超过1M
            if (txtFileUp.PostedFile.ContentLength > 1024000)
            {
                fileOk = false;
            }
            //最后的结果
            if (!fileOk)
            {
                TierService.MessageBox.Show(this, "文件类型错误或者文件大小超出１Ｍ");
                return;
            }

            if (Directory.Exists(path) == false)
                Directory.CreateDirectory(path); //如果没就创建一个目录；

            #endregion

            try
            {
                sFullFileName = path + txtFileUp.FileName;
                txtFileUp.PostedFile.SaveAs(sFullFileName);
            }
            catch (Exception ep)
            {
                TierService.MessageBox.Show(this, "上传文件失败,原因为：" + ep.Message);
                return;
            }
        }


        string sImpBatchNo = "";
        if (txtIMPBATCHNO.Text == "")
        {
            sImpBatchNo = TranUtils.GetImpBatchNo();
        }
        else
        {
            sImpBatchNo = txtIMPBATCHNO.Text;
        }

        string lineStr = "";
        if (File.Exists(sFullFileName))
        {
            StreamReader re = File.OpenText(sFullFileName);
            try
            {
                List<T_IMPCARD> mImpCardList = new List<T_IMPCARD>();
                while ((lineStr = re.ReadLine()) != null)
                {
                    try
                    {
                        string[] CardList = lineStr.Split(',');
                        T_IMPCARD mImpCard = new T_IMPCARD();
                        mImpCard.IMPBATCHNO = sImpBatchNo;
                        mImpCard.CARDNO = CardList[0].ToString();
                        mImpCard.CARDPWD = CardList[1].ToString();
                        mImpCardList.Add(mImpCard);
                    }
                    catch (Exception)
                    {
                    }
                }
                bool bDataUpLoad = DataUpLoad(mImpCardList, sImpBatchNo);
            }
            finally
            {
                re.Close();
                File.Delete(sFullFileName);
            }
        }
        else
        {
            TierService.MessageBox.Show(this, "打开文件失败");
        }
    }

    protected void btnCardDelete_Click(object sender, EventArgs e)
    {
        string ac_impbatchno = "";
        if (txtIMPBATCHNO.Text != "")
        {
            ac_impbatchno = txtIMPBATCHNO.Text;
            T_PRODUCTIMP.DeleteProductItem(ac_impbatchno);

            T_PRODUCTITEM mProductItem = new T_PRODUCTITEM();
            DataSet ds = mProductItem.GetProductItemListByImpBatchNo(ac_impbatchno);
            gridSearchResult.DataSource = ds.Tables[0];
            gridSearchResult.DataBind();
        }
        else
        {
            ac_impbatchno = (string)ViewState[ImpBatchNo];
            if (TierService.Utility.IsNullorEmpty(ac_impbatchno))
            {
                TierService.MessageBox.Show(this, "没有卡号信息,不能删除");
                return;
            }

            T_IMPCARD.DeleteImpCard(ac_impbatchno);

            BindImpCardList(ac_impbatchno);
        }



    }

    private void BindImpCardList(string ac_impbatchno)
    {
        DataTable dt = T_IMPCARD.GetImpCardList(ac_impbatchno).Tables[0];
        gridSearchResult.DataSource = dt;
        gridSearchResult.DataBind();
        ViewState[ImpBatchNo] = ac_impbatchno;
        ViewState["data"] = dt;
    }

    private bool DataUpLoad(List<T_IMPCARD> mImpCardList, string sImpBatchNo)
    {
        try
        {
            T_IMPCARD.ImpData(mImpCardList);
            BindImpCardList(sImpBatchNo);
            return true;
        }
        catch (Exception ex)
        {
            string sErrorMessage = TierService.PageValidate.RemoveChr10And13(ex.Message);
            string sOraError = sErrorMessage.Substring(0, 9);
            if (sOraError == "ORA-00001")
                TierService.MessageBox.Show(this.Page, "数据导入失败,错误原因为：此批导入数据存在重复卡号");
            else
                TierService.MessageBox.Show(this.Page, "数据导入失败,错误原因为：" + sErrorMessage);
            return false;
        }
    }

    protected void btnSubmitAuditCallBack_CallBack(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
        string ac_ImpBatchNo = e.Parameter;
        string ac_userid = base.CurrentUserCode;
        string ac_status = "0";
        Int32 ai_result = 0;
        string ac_result = "";

        //AC_STATUS 0 :提交审核  1 退回审核  2 审核 
        T_IMPCARD.IMP_PRODUCT_ITEM_ADUIT(ac_ImpBatchNo, ac_userid, ac_status, ref ai_result, ref ac_result);
        if (ai_result == 0)
        {
            e.Result = "ok";
        }
        else
        {
            e.Result = ac_result;

        }
    }

    protected void btnCancelAuditCallBack_CallBack(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
        string ac_ImpBatchNo = e.Parameter;
        string ac_userid = base.CurrentUserCode;
        string ac_status = "1";
        Int32 ai_result = 0;
        string ac_result = "";

        //AC_STATUS 0 :提交审核  1 退回审核  2 审核 
        T_IMPCARD.IMP_PRODUCT_ITEM_ADUIT(ac_ImpBatchNo, ac_userid, ac_status, ref ai_result, ref ac_result);
        if (ai_result == 0)
        {
            e.Result = "ok";
        }
        else
        {
            e.Result = ac_result;

        }
    }

    protected void btnAuditCallback_CallBack(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
        string ac_ImpBatchNo = e.Parameter;
        string ac_userid = base.CurrentUserCode;
        string ac_status = "2";
        Int32 ai_result = 0;
        string ac_result = "";

        //AC_STATUS 0 :提交审核  1 退回审核  2 审核 
        T_IMPCARD.IMP_PRODUCT_ITEM_ADUIT(ac_ImpBatchNo, ac_userid, ac_status, ref ai_result, ref ac_result);
        if (ai_result == 0)
        {
            e.Result = "ok";
        }
        else
        {
            e.Result = ac_result;

        }
    }


    protected void btnID_Click(object sender, EventArgs e)
    {
        LoadProduct(txtProductId.Text.Trim());
    }
}